package com.zrb.mobile.utility;

import org.apache.http.Header;

import android.content.Context;
import android.location.Location;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.zrb.mobile.R;
import com.zrb.mobile.adapter.Project_CitylistAdapter;
import com.zrb.mobile.adapter.model.CityDto;
import com.zrb.mobile.adapter.model.CityDtos;
import com.zrb.mobile.utility.PopBuilder.onDismissListener;

public class PopupCity  implements  AMapLocationListener {

	
	 View mAnchor;
 	 Context mcontext;
 	 int curCode;
 	 String curName;
 	 onCitySelectListener monCitySelectListener;
 	 public interface onCitySelectListener {
  		 void onCitySelectEvent(String name,int PostCode);
 	 }
 	 
 	 public void setonCitySelectListener(onCitySelectListener  onCitySelectListener){
  		monCitySelectListener=onCitySelectListener;
 	 }
 	 
	 private LocationManagerProxy mLocationManagerProxy;
	 public PopupCity(Context context){
 		 mcontext =context;
	 }
	 
	 public void setAnchor(View Anchor){
 		 mAnchor=Anchor;
	 }
	 
	 Project_CitylistAdapter mcitylistAdapter;
	 PopupWindow mPopupWindow;
	 ListView mPopuplist;
	 TextView mtv_areaload;
	  public void showPop(int postCode,String privince)  {
         if (mPopupWindow != null)
         {
             if (!mPopupWindow.isShowing()) {
            	 curCode=postCode;
            	 curName=privince;
            	 if(null!=mcitylistAdapter) mcitylistAdapter.UpdateIndex(postCode);
                 /*最重要的一步：弹出显示   在指定的位置(parent)  最后两个参数 是相对于 x / y 轴的坐标*/
                 mPopupWindow.showAtLocation(mAnchor,Gravity.BOTTOM , 0, 0);
             }
         }
         else {
       	  PopBuilder tmp = new PopBuilder(mcontext);
             tmp.setContentView(R.layout.popup_city_choose) ;
             tmp.getRootView().findViewById(R.id.listView1);
             
             tmp.getRootView().findViewById(R.id.close_city_img).setOnClickListener(myClickListener);
             
             tmp.getRootView().findViewById(R.id.tv_temp_allarea).setOnClickListener(myClickListener);
             tmp.getRootView().findViewById(R.id.layout_arealoading).setOnClickListener(myClickListener);; 
             
             mtv_areaload=(TextView)tmp.getRootView().findViewById(R.id.tv_areaload);
             mPopuplist=(ListView)tmp.getRootView().findViewById(R.id.listView1);
             mPopuplist.setOnItemClickListener(new OnItemClickListener(){

				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
					// TODO Auto-generated method stub
					 CityDto curCity= mcitylistAdapter.CurrentDatas.get(arg2);
					if(null!=mcitylistAdapter) mcitylistAdapter.UpdateIndex(curCity.postcode);
 				
					
					 curCode=curCity.postcode;
					 curName=curCity.cityName;
 					 if(null!=mPopupWindow) mPopupWindow.dismiss();
 					 
 					
 				//	if(null!=monCitySelectListener) monCitySelectListener.onCitySelectEvent(curCity.cityName, curCity.postcode);
			/*		txt_locationBtn.setText(curCity.cityName);
					curPostcode=curCity.postcode;//
*/	 				
				   
				   /*	msearchResults.setRefreshing(true);*/
				}
              });
              tmp.setonDismissListener(new onDismissListener(){
				  @Override
				  public void onPopupClose() {
 					//reset();
					  if(null!=monCitySelectListener) monCitySelectListener.onCitySelectEvent(curName, curCode);
			 	  }
             } );
             mPopupWindow = tmp.Create();
             mPopupWindow.showAtLocation(mAnchor, Gravity.BOTTOM, 0, 0);
             init();
             LoadArea();
         }
     }
  
    OnClickListener myClickListener=new OnClickListener(){

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
		   switch(v.getId()){
		      case R.id.close_city_img:
       	      //reset();
       	      if(null!=mPopupWindow) mPopupWindow.dismiss();
       	   break;
              case R.id.layout_arealoading:
       	       showGpsArea();
  			   break;
  		   case R.id.tv_temp_allarea:
  			 curCode=0;
			 curName="全国";
  			 if(null!=mPopupWindow) mPopupWindow.dismiss();
  			/* if(null!=monCitySelectListener)
  				 monCitySelectListener.onCitySelectEvent("全国", 0);*/
  		   	 //  curPostcode=0;
  		      // txt_locationBtn.setText("全国");
  			  // if(null!=mPopupWindow) mPopupWindow.dismiss();
  			  // msearchResults.setRefreshing(true);
  			break;
	        }
		} 
	 };
	  
	 private void showGpsArea() {

/*		if (mtv_areaload.getTag() == null) return;
 		txt_locationBtn.setText(mtv_areaload.getText().toString().split(" ")[0]);
		curPostcode=Integer.parseInt(mtv_areaload.getTag().toString().substring(0, 2) + "0000");//
		if(null!=mPopupWindow) mPopupWindow.dismiss();
			msearchResults.setRefreshing(true);*/
		 if (mtv_areaload.getTag() == null) return;
 		 curName=mtv_areaload.getText().toString().split(" ")[0];
		 curCode=Integer.parseInt(mtv_areaload.getTag().toString().substring(0, 2) + "0000");
		 
		 if(null!=mPopupWindow) mPopupWindow.dismiss();
	 }
	  
	 private void LoadArea() {
		// areaApi/findCityByProvince
 		ZrbRestClient.get("areaApi/findAllProvince", null, new AsyncHttpResponseHandler() {
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2, Throwable arg3) {
 				// progTip.Dismiss();
				CommonUtil.showToast("加载数据出错！", mcontext);
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				// TODO Auto-generated method stub
				String results = new String(arg2);
				try {
					Gson gson = new Gson();
					CityDtos tmpDto = gson.fromJson(results, CityDtos.class);
					if (tmpDto.res == 1) {
						if (mcitylistAdapter == null) {
							mcitylistAdapter = new Project_CitylistAdapter(mcontext);
							mcitylistAdapter.CurrentDatas.addAll(tmpDto.data);
							mPopuplist.setAdapter(mcitylistAdapter);
						}
					} else
						CommonUtil.showToast(tmpDto.msg,mcontext);
				} catch (Exception e) {
					CommonUtil.showToast("加载数据出错！", mcontext);
 				}
			}
		});
	}

	
	/**
	 * 初始化定位
	 */
	private void init() {
		// 初始化定位，只采用网络定位
		mLocationManagerProxy = LocationManagerProxy.getInstance(mcontext);
		mLocationManagerProxy.setGpsEnable(false);
		// 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
		// 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用removeUpdates()方法来取消定位请求
		// 在定位结束后，在合适的生命周期调用destroy()方法
		// 其中如果间隔时间为-1，则定位只定一次,
		// 在单次定位情况下，定位无论成功与否，都无需调用removeUpdates()方法移除请求，定位sdk内部会移除
		mLocationManagerProxy.requestLocationData(
				LocationProviderProxy.AMapNetwork, 60 * 1000, 15, this);
	}

 
	public void onPause() {
		//super.onPause();
		if (mLocationManagerProxy != null) {
			// 移除定位请求
			mLocationManagerProxy.removeUpdates(this);
			// 销毁定位
			mLocationManagerProxy.destroy();
		}
	} 
	 
	 @Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderDisabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onProviderEnabled(String provider) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onStatusChanged(String provider, int status, Bundle extras) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onLocationChanged(AMapLocation amapLocation) {
		// TODO Auto-generated method stub
		if (amapLocation != null && amapLocation.getAMapException().getErrorCode() == 0) {
 			 mtv_areaload.setText(amapLocation.getProvince() + " " + amapLocation.getCity());
			  mtv_areaload.setTag(amapLocation.getAdCode()); 
			
	    }
   }
}
